<?php

namespace App\Http\Controllers;

use App\Helpers\ResponseHelper;
use App\Models\BalanceRecord;
use App\Models\CancelOrderLog;
use App\Models\Commission;
use App\Models\MissionDeposit;
use App\Models\Order;
use App\Models\ProceedList;
use App\Models\RunErrand;
use App\Models\WithdrawFund;
use App\Services\Facades\OrderService;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class OrderController extends Controller
{
    /**
     * 任务列表
     *
     * @return JsonResponse
     */
    public function index(Request $request): JsonResponse
    {
        $limit = $request->get('limit', 20);
        $schoolId = $request->get('school_id');
        $type = $request->get('type', 1);
        if (!$schoolId) {
            return ResponseHelper::error(message: '数据异常');
        }
        $orderList = Order::with(['user'])->where('school_id', $schoolId)->where('type', $type)->where('status', 3)->orderBy('id', 'desc')->paginate($limit);
        return ResponseHelper::success(data: [
            'list' => $orderList->items(),
            'total' => $orderList->total(),
        ]);
    }

    /*
     * 任务详情
     */
    public function detail(Request $request)
    {
        $orderId = $request->input('order_id');
        $order = Order::with(['user', 'school', 'unitBlock'])->where('id', $orderId)->first();
        if (!$order) {
            return ResponseHelper::error(message: '数据异常');
        }
        return ResponseHelper::success(data: $order);


    }

    /**
     * 发布任务
     *
     * @param \Illuminate\Http\Request $request
     * @return JsonResponse|Response
     */
    public function store(Request $request): Response|JsonResponse
    {
        $user = $request->user();
        $type = $request->get('type');
        $orderId = $request->get('order_id');
        if (($type != 1 && $type != 2)) {
            return ResponseHelper::error(message: '数据异常');
        }
        $amount = $handlingFee = $orderTakingFee = 0;
        if ($type == 1) {
            $validator = Validator::make($request->all(), [
                'mobile' => ['required', 'regex:/^1[3-9]\d{9}$/'],
                'type' => 'required',
                'school_id' => 'required',
                'unit_block_id' => 'required',
                'room_number' => 'required',
                'commission_id' => 'required',
                'cut_off_at' => 'required',
                'description' => 'required',
            ]);
            if (!$request->input('commission_id')) {
                return ResponseHelper::error(message: '数据异常');
            }
            //如果是跑腿任务，查看佣金配置
            $commission = Commission::findOrFail($request->input('commission_id'));
            $amount = $commission->price;
            $handlingFee = $commission->service_charge;
            $orderTakingFee = $commission->ordering_fee;
            if ($orderTakingFee < 0.01 && $orderTakingFee > 0) {
                $orderTakingFee = 0.01;
            }
        } elseif ($type == 2) {
            $validator = Validator::make($request->all(), [
                'mobile' => ['required', 'regex:/^1[3-9]\d{9}$/'],
                'type' => 'required',
                'school_id' => 'required',
                'amount' => 'required',
                'cut_off_at' => 'required',
                'description' => 'required',
            ]);
            $amount = $request->input('amount');
            if ($amount < 0.5) {
                return ResponseHelper::error(message: '最低金额需要大于0.5');
            }
            $handlingFee = 0;
            //如果是其他任务，计算骑手需缴纳保证金
            $missionDeposit = MissionDeposit::where('school_id', $request->input('school_id'))->first();
            if ($missionDeposit) {
                $orderTakingFee = round($amount * $missionDeposit->percentage / 100, 2);
                if ($orderTakingFee < 0.01 && $orderTakingFee > 0) {
                    $orderTakingFee = 0.01;
                }
            }
        }

        if ($validator->fails()) {
            $messages = '';
            $errors = $validator->errors();
            foreach ($errors->all() as $message) {
                $messages .= $message . PHP_EOL;
            }
            return ResponseHelper::error(message: $messages);
        }
        if ($amount < 0.01) {
            return ResponseHelper::error(message: '价格不能为小于0.01');
        }

        $order = Order::where('user_id', $user->id)->where('id', $orderId)->first();
        if ($order) {
            if ($order->status != 4) {
                return ResponseHelper::error(message: '该任务不能重新编辑');
            }
            $orderNumber = $order->order_number;
            $writeOffCode = $order->write_off_code;
            $writeOffCodeUrl = $order->write_off_code_url;
            $amount = $order->amount;
            $handlingFee = $order->handling_fee;
            $orderTakingFee = $order->order_taking_fee;
            $type = $order->type;
            $status = 2;
        } else {
            $orderNumber = OrderService::generateOrderNumber($type);
            $writeOffCode = OrderService::generateWriteOffCode();
            $writeOffCodeUrl = OrderService::generateQrCode($writeOffCode);
            $status = 1;
        }
        if ($request->input('cut_off_at') <= Carbon::now()) {
            return ResponseHelper::error(message: '该任务截止时间错误');
        }
        try {
            // 开始事务
            DB::beginTransaction();
            Order::updateOrCreate([
                'id' => $orderId,
            ],
                [
                    'order_number' => $orderNumber,
                    'write_off_code' => $writeOffCode,
                    'write_off_code_url' => $writeOffCodeUrl,
                    'user_id' => $user->id,
                    'mobile' => $request->input('mobile'),
                    'school_id' => $request->input('school_id'),
                    'type' => $type,
                    'unit_block_id' => $request->input('unit_block_id') ?? null,
                    'room_number' => $request->input('room_number') ?? null,
                    'amount' => $amount,
                    'handling_fee' => $handlingFee,
                    'order_taking_fee' => $orderTakingFee,
                    'cut_off_at' => $request->input('cut_off_at'),
                    'pickup_code' => $request->input('pickup_code') ?? null,
                    'description' => $request->input('description'),
                    'images' => $request->input('images'),
                    'status' => $status
                ]);
            if ($status == 1) {
                //如果是新建任务，发起微信支付，审核驳回的任务重新提交，不需要再微信支付
                $result = OrderService::weChatPayment($user, $orderNumber, bcadd($amount, $handlingFee, 2), 1);
                $result = json_decode($result->content(), true);
            } else {
                $result = [
                    'status' => 'success',
                    'message' => ''
                ];
            }
            if ($result['status'] == 'success') {
                // 提交事务
                DB::commit();
                return ResponseHelper::success(data: $result['data'], message: '发布成功');
            } else {
                DB::rollBack();
                return ResponseHelper::error(message: $result['message']);
            }
        } catch (\Exception $e) {
            // 发生错误，回滚事务
            DB::rollBack();
            return ResponseHelper::error(message: $e->getMessage());
        }
    }

    /*
     * 跑腿-我的任务列表
     * */
    public function orderList(Request $request)
    {
        $user = $request->user();
        $runErrand = RunErrand::where('user_id', $user->id)->first();
        if (!$runErrand) {
            return ResponseHelper::error(message: '暂无数据');
        }
        $limit = $request->get('limit', 20);
        $status = $request->get('status', 5);
        $orderList = Order::with(['user', 'school'])->where('status', $status)->whereIn('status', [5, 6])->where('run_errand_id', $runErrand->id)->orderBy('cut_off_at', 'asc')->paginate($limit);

        return ResponseHelper::success(data: [
            'list' => $orderList->items(),
            'total' => $orderList->total(),
        ]);
    }

    /*
     * 跑腿-接单
     * */
    public function takeOrder(Request $request)
    {
        $user = $request->user();
        $orderId = $request->input('order_id');
        $runErrand = RunErrand::where('user_id', $user->id)->first();
        if (!$runErrand) {
            return ResponseHelper::error(message: '暂无数据');
        }
        if ($runErrand->blacklists == 2) {
            return ResponseHelper::error(message: '你已被系统设为黑名单，请联系校园代理');
        }
        $order = Order::where('id', $orderId)->first();
        if ($order) {
            if ($order->status != 3) {
                return ResponseHelper::error(message: '该任务不能接单');
            }
            //查看跑腿是否接过该任务
            /*$proceed = ProceedList::where('user_id', $user->id)->where('order_id', $orderId)->first();
            if ($proceed) {
                return ResponseHelper::error(message: '你不能接该任务');
            }*/
            try {
                // 开始事务
                DB::beginTransaction();
                //创建收益列表
                $orderNumber = OrderService::generateOrderNumber(3);
                ProceedList::create([
                    'order_number' => $orderNumber,
                    'user_id' => $user->id,
                    'order_id' => $orderId,
                    'status' => 3
                ]);

                //如果该任务需要支付金额，调起微信支付
                if ($order->order_taking_fee >= 0.01) {
                    $result = OrderService::weChatPayment($user, $orderNumber, $order->order_taking_fee, 1);
                    $result = json_decode($result->content(), true);
                    if ($result['status'] == 'success') {
                        // 提交事务
                        DB::commit();
                        return ResponseHelper::success(data: $result['data'], message: '请支付');
                    } else {
                        DB::rollBack();
                        return ResponseHelper::error(message: $result['message']);
                    }
                }
                // 提交事务
                DB::commit();
            } catch (\Exception $e) {
                // 发生错误，回滚事务
                DB::rollBack();

                // 处理异常
                return ResponseHelper::error(message: $e->getMessage());
            }
            return ResponseHelper::success(data: [], message: '接单成功');
        } else {
            return ResponseHelper::error(message: '任务异常');
        }
    }

    /*
     * 跑腿-取消任务
     * */
    public function cancelOrder(Request $request)
    {
        $user = $request->user();
        $orderId = $request->input('order_id');
        $runErrand = RunErrand::where('user_id', $user->id)->first();
        if (!$runErrand) {
            return ResponseHelper::error(message: '暂无数据');
        }
        $order = Order::where('id', $orderId)->where('run_errand_id', $runErrand->id)->first();
        if (!$order) {
            return ResponseHelper::error(message: '数据异常');
        }
        if ($order->status != 5) {
            return ResponseHelper::error(message: '该任务不能取消接单');
        }
        if($order->cut_off_at <= Carbon::now()){
            return ResponseHelper::error(message: '该订单已经超过截止时间，无法取消订单');
        }
        try {
            // 开始事务
            DB::beginTransaction();
            $order->status = 3;
            $order->run_errand_id = null;
            $order->save();
            //创建取消接单记录
            CancelOrderLog::create([
                'run_errand_id' => $runErrand->id,
                'order_id' => $orderId,
            ]);
            //收益列表状态更新
            $proceedList = ProceedList::where('user_id', $user->id)->where('order_id', $order->id)->where('status', 1)->first();
            if ($proceedList) {
                $proceedList->status = 3;
                $proceedList->save();
            }
            //如果跑男支付接单费用，发起微信退款
            if ($order->order_taking_fee >= 0.01) {
                OrderService::refund($proceedList->order_number, $order->order_taking_fee, $order->order_taking_fee, 2);
            }
            // 提交事务
            DB::commit();
        } catch (\Exception $e) {
            // 发生错误，回滚事务
            DB::rollBack();

            // 处理异常
            return ResponseHelper::error(message: $e->getMessage());
        }
        //查询该跑男本月是否已经取消3单，如果是，把该跑男拉入黑名单
        if ($runErrand->blacklists == 1) {
            $cancelOrderLogCount = CancelOrderLog::where('run_errand_id', $runErrand->id)->whereMonth('created_at', Carbon::now()->month)->count();
            if ($cancelOrderLogCount >= 3) {
                $runErrand->blacklists = 2;
                $runErrand->save();
            }
        }
        return ResponseHelper::success(message: '取消成功');
    }

    /*
     * 完成任务
     * */
    public function completeOrder(Request $request)
    {
        $user = $request->user();
        $orderId = $request->input('order_id');
        $writeOffCode = $request->input('write_off_code');
        $runErrand = RunErrand::where('user_id', $user->id)->first();
        if (!$runErrand) {
            return ResponseHelper::error(message: '暂无数据');
        }
        $order = Order::where('id', $orderId)->where('run_errand_id', $runErrand->id)->first();
        if (!$order) {
            return ResponseHelper::error(message: '数据异常');
        }
        if ($order->status != 5) {
            return ResponseHelper::error(message: '该任务不能完成');
        }
        if ($order->write_off_code != $writeOffCode) {
            return ResponseHelper::error(message: '核销码不正确');
        }
        try {
            // 开始事务
            DB::beginTransaction();
            $order->status = 6;
            $order->save();
            //收益列表状态更新
            $proceedList = ProceedList::where('user_id', $user->id)->where('order_id', $order->id)->where('status', 1)->first();
            if ($proceedList) {
                $proceedList->status = 2;
                $proceedList->save();
            }
            //跑腿用户钱包更新、创建钱包记录
            BalanceRecord::create([
                'user_id' => $user->id,
                'type' => 1,
                'amount' => $order->amount,
            ]);
            $user->balance = bcadd($user->balance, $order->amount, 2);
            $user->save();
            // 提交事务
            DB::commit();
        } catch (\Exception $e) {
            // 发生错误，回滚事务
            DB::rollBack();

            // 处理异常
            return ResponseHelper::error(message: $e->getMessage());
        }
        return ResponseHelper::success(message: '任务已完成');
    }

    public function qrcode(Request $request)
    {
        $code = $request->input('write_off_code');

    }
}
